package com.heima.media.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.WmNewsService;
import com.heima.model.common.dtos.PageRequestDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.dto.WmNewsDto;
import com.heima.model.wemedia.pojos.dto.WmNewsQueryDto;
import com.heima.model.wemedia.pojos.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult searchNews(PageRequestDto<WmNewsQueryDto> requestDto) {
        WmNewsQueryDto wmNewsQuery = requestDto.getBody();
        List<WmNews> wmNews = wmNewsMapper.searchNews(wmNewsQuery);
        System.out.println(wmNews);
        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //2）完善
        //2.1）手动转换图片images，图片用逗号拼接
        //2.2）封面处理，单图：1、三图：3、无图：0、自动：-1
        //     自动处理：从内容中提取图片
        if (dto.getType().intValue() == -1) {
            //获取内容的图片
            dto.setImages(contentImages(dto.getContent()));
        }
        if (dto.getImages()!=null&&dto.getImages().size()>0){
            wmNews.setImages(StringUtils.join(dto.getImages().size()>3? dto.getImages().subList(0,2)
                    :dto.getImages(),","));
        }
        if (wmNews.getStatus().intValue()==1){
            wmNews.setSubmitedTime(new Date());
        }
        if (wmNews.getId()==null){
            wmNews.setCreatedTime(new Date());
            wmNewsMapper.insert(wmNews);
        }else {
            UpdateWrapper<WmNews> wrapper = new UpdateWrapper<WmNews>();
            wrapper.eq("id",wmNews.getId());
            wrapper.eq("user_id",wmNews.getUserId());
            wmNewsMapper.update(wmNews,wrapper);
        }
        if (wmNews.getStatus().intValue()==1){
            Map<String, Object> resultmap = verifyContent(wmNews);
            kafkaTemplate.send("verifyArticle",JSON.toJSONString(resultmap));
        }
        return ResponseResult.okResult(null);
    }

    /**
     * 状态审核处理
     * @param result
     * @param id
     * @param date
     */
    @Override
    public void modifyStatus(String result, Integer id, Date date) {
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        switch (result){
            case "pass":
                wmNews.setStatus(9);
                if (date!=null&&date.getTime()>System.currentTimeMillis()){
                    wmNews.setStatus(8);
                }
                break;
            case "review":
                wmNews.setStatus(3);
                break;
            case "block":
                wmNews.setStatus(2);
        }
        wmNewsMapper.updateById(wmNews);
    }

    @Override
    public List<WmNews> publishArticles() {
        QueryWrapper<WmNews> wmNewsQueryWrapper = new QueryWrapper<>();
        wmNewsQueryWrapper.eq("status",8);
        wmNewsQueryWrapper.eq("publish_time",new Date());
        return wmNewsMapper.selectList(wmNewsQueryWrapper);
    }

    @Override
    public void updateStatus(List<WmNews> wmNews) {
        for (WmNews wmNew : wmNews) {
            wmNewsMapper.updateById(wmNew);
        }
    }

    @Override
    public void upOrDown(Integer id, Integer updown) {
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        wmNews.setEnable(updown);
        wmNewsMapper.updateById(wmNews);
        WmNews news = wmNewsMapper.selectById(id);
        if (news.getStatus()==9){
            Map<Long,Integer> dateMap=new HashMap<>();
            dateMap.put(id.longValue(),updown);
            kafkaTemplate.send("syncarticle",JSON.toJSONString(dateMap));
        }


    }

    public Map<String,Object> verifyContent(WmNews wmNews){
        Map<String,Object> dateMap=new HashMap<>();
        List<String> contentTexts = contentTexts(wmNews);
        contentTexts.add(wmNews.getTitle());
        dateMap.put("text",contentTexts);
        List<String> images = contentImages(wmNews.getContent());
        if (wmNews.getImages()!=null&&wmNews.getImages().contains("http")){
            images.addAll(Arrays.asList(wmNews.getImages().split(",")));
        }
        dateMap.put("images",images);
        dateMap.put("backQueue","verifyArticle");
        return dateMap;
    }

    /**
     * 获取文章内容
     * @param dto
     * @return
     */
    public List<String> contentTexts(WmNews dto) {
        List<Map> mapList = JSON.parseArray(dto.getContent(), Map.class);
        List<String> texts = new ArrayList<String>();
        for (Map map : mapList) {
            String type = map.get("type").toString();
            if (type.equals("text")) {
                texts.add(map.get("value").toString());
            }
        }
        return texts;
    }

    /**
     * 获取蹄片内容
     * @param dto
     * @return
     */
    public List<String> contentImages(String content) {
        List<Map> mapList = JSON.parseArray(content, Map.class);
        List<String> imags = new ArrayList<String>();
        for (Map map : mapList) {
            String type = map.get("type").toString();
            if (type.equals("image")) {
                imags.add(map.get("value").toString());
            }
        }
        return imags;
    }
}
